import uuid
import hashlib
import time
import random
import requests


# 生成nonce值
def gen_nonce():
    i2 = 16
    string_buffer = []
    for i3 in range(i2):
        string_buffer.append(
            "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[random.randint(0, 61)])
    string_buffer = ''.join(string_buffer)
    return string_buffer


# 生成时间戳
def timestamp():
    time_ = str(int(time.time()))
    return time_


# 生成sign值
def gen_sign(info, url):
    # 因为java有排序 在python中需要sorted来调整,sorted是根据acill码点进行排序
    result = "&".join([f"{key}={info[key]}" for key in sorted(info.keys())])
    # print("这是经过排序后的格式:", result)

    # 加密前的明文
    str_sign = url + result + 'aA4@ud^926U(}^r9'
    # print("这是加密前的明文:", str_sign)

    obj = hashlib.md5()
    byte = obj.update(str_sign.encode('utf-8'))
    hex_string = obj.hexdigest()

    # 对二进制进行hash
    hash_bytes = obj.digest()

    # 将字节字符串转换为字符数组
    hash_array = list(hash_bytes)

    a = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]

    def b(byte):
        i2 = int(byte) // 16
        # print(i2)
        sb = ''
        strArr = a
        sb += strArr[i2]
        sb += strArr[byte % 16]
        return sb

    def c(bArr):
        stringBuffer = ""
        for byte in bArr:
            stringBuffer += b(byte)
        return stringBuffer

    # sign值：
    g_sign = c(hash_array)
    return g_sign


def run():
    # 获取auth的时间戳
    global authorization
    auth_time = timestamp()
    # 获取UUID
    x_device_udid = uuid.uuid4()
    x_device_uuid = str(x_device_udid).replace("-", "")

    # 获取auth_nonce
    auth_nonce = gen_nonce()
    print('生成auth_nonce:', auth_nonce)

    # authorization的sign传入的信息
    authorization_info = {
        "name": "Google%20Pixel2XL",
        "nonce": auth_nonce,
        "platform": "udid",
        "timestamp": auth_time,
        "udid": x_device_udid  # 164051e9-f063-3797-ae5b-c23397460a1f
    }

    # authenticate_url要参与sign生成
    authenticate_url = "https://api2.tophub.app/account/authenticate"

    # 获取auth_sign签名
    auth_sign = gen_sign(authorization_info, authenticate_url)
    print('生成auth_sign:', auth_sign)

    # 构造请求头
    hearder = {
        "accept": "application/vnd.tophub.v1+json",
        "user-agent": "TophubApp/1.0 Mozilla/5.0 (Linux; Android 11; Pixel 2 XL Build/RP1A.201005.004.A1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/118.0.0.0 Mobile Safari/537.36",
        "x-network-type": "NETWORK_WIFI",
        "x-app-version": "18",
        "x-app-package-name": "today.tophub.app",
        "x-app-version-name": "1.9.3",
        "x-device-uuid": str(x_device_uuid),
        "x-device-model": "Pixel2XL",
        "x-device-udid": str(x_device_udid),
        "content-type": "application/x-www-form-urlencoded",
        "content-length": "160",
        "accept-encoding": "gzip"
    }
    # print(hearder)

    # 构造请求体
    datas = {
        "name": "Google Pixel2XL",
        "nonce": auth_nonce,
        "platform": "udid",
        "sign": auth_sign,
        "timestamp": auth_time,
        "udid": str(x_device_udid)
    }
    # print(datas)

    '''
    try:
        # 模拟发送请求
        auth_res = requests.post(url=authenticate_url, data=datas, headers=hearder)
        # print(auth_res.json()['data']['token'])
        authorization = auth_res.json()['data']['token']
        print('获取的authenticate为：', authorization)

    except Exception as e:
        print("获取的authenticate失败！！！！！！！！！", e)
    '''

    # 生成/nodes/5666的nonce
    nodes_nonce = gen_nonce()

    # 获取nodes_time的时间戳
    nodes_time = timestamp()

    # nodes_info的
    nodes_info = {
        "last_items_count": 0,
        "nonce": nodes_nonce,
        "timestamp": nodes_time,
    }

    # url要参与sign的生成
    url_data = 'https://api2.tophub.app/nodes/5666'

    # 获取nodes_sign签名
    nodes_sign = gen_sign(nodes_info, url_data)

    # 构建新的请求头
    hearder['authorization'] = auth_sign

    # 请求参数
    params = {
        "last_items_count": "0",
        "nonce": nodes_nonce,
        "sign": nodes_sign,
        "timestamp": nodes_time
    }

    try:
        nodes_res = requests.get(url=url_data, params=params, headers=hearder, timeout=5)
        print(nodes_res.status_code, '\n', nodes_res.json())
    except Exception as e:
        print("获取数据失败，请重试！！！！", e)


if __name__ == '__main__':
    run()
